<template>
  <div class="discover-bg">
    <div class="discover-container">
      <!-- 用户操作统计区域 -->
      <div class="user-stats">
        <div class="stats-item">
          <span class="stats-label">已点赞</span>
          <span class="stats-count">{{ getUserActionStats().likedCount }}</span>
        </div>
        <div class="stats-item">
          <span class="stats-label">已收藏</span>
          <span class="stats-count">{{
            getUserActionStats().starredCount
          }}</span>
        </div>
        <div class="stats-item">
          <span class="stats-label">已评论</span>
          <span class="stats-count">{{
            getUserActionStats().commentCount
          }}</span>
        </div>
        <button class="clear-btn" @click="clearAllUserActions">清除记录</button>
        <button class="sync-btn" @click="syncWithServer">同步数据</button>
        <button class="debug-btn" @click="showDebugInfo">调试信息</button>
        <button class="login-btn" @click="openLoginModal">登录</button>
      </div>

      <div v-for="post in posts" :key="post.id" class="post-card">
        <!-- 右上角操作菜单 -->
        <div class="post-actions">
          <div class="dots-btn" @click.stop="toggleMenu(post.id)">
            <svg width="28" height="28" viewBox="0 0 28 28">
              <circle cx="7" cy="14" r="2" fill="#00b2b1" />
              <circle cx="14" cy="14" r="2" fill="#00b2b1" />
              <circle cx="21" cy="14" r="2" fill="#00b2b1" />
            </svg>
          </div>
          <div v-if="activeMenuId === post.id" class="action-menu" @click.stop>
            <div class="arrow-up"></div>
            <div class="menu-item" @click="handleNotInterested(post)">
              不感兴趣
            </div>
            <div class="menu-item" @click="handleReport(post)">举报</div>
          </div>
        </div>

        <!-- 帖子内容 -->
        <div class="post-header">
          <img class="avatar" :src="getUserAvatar(post.user)" alt="avatar" />
          <div class="user-info">
            <div class="user-name">
              {{ getUserName(post.user) }}
              <span class="user-tag">（互关互赞）</span>
            </div>
          </div>
        </div>
        <div class="post-title">
          <b>{{ post.title }}</b>
        </div>
        <div class="post-content">{{ post.content }}</div>
        <div v-if="post.image" class="post-image">
          <img :src="getPostImageUrl(post.image)" alt="post image" />
        </div>
        <!-- 互动按钮区 -->
        <div class="post-footer">
          <span
            class="footer-item"
            @click="handleLike(post)"
            :style="{ color: likedMap[post.id] ? '#ff4d4f' : '#888' }"
          >
            <svg viewBox="0 0 24 24" class="icon-svg">
              <path
                d="M12.1 8.64l-.1.1-.11-.1C9.14 6.24 5.6 7.91 5.6 11.28c0 2.54 2.04 4.58 5.4 7.05 3.36-2.47 5.4-4.51 5.4-7.05 0-3.37-3.54-5.04-5.29-2.64z"
                :fill="likedMap[post.id] ? '#ff4d4f' : 'none'"
                :stroke="likedMap[post.id] ? '#ff4d4f' : '#999'"
                stroke-width="1.5"
              />
            </svg>
            {{ post.like_count }}
          </span>
          <span class="footer-item" @click="handleShowComments(post)">
            <svg viewBox="0 0 24 24" class="icon-svg">
              <path
                d="M21 6.5a2.5 2.5 0 0 0-2.5-2.5h-13A2.5 2.5 0 0 0 3 6.5v7A2.5 2.5 0 0 0 5.5 16H7v3l4-3h5.5A2.5 2.5 0 0 0 19 13.5v-7z"
                fill="none"
                stroke="#999"
                stroke-width="1.5"
              />
            </svg>
            {{ post.comment_count }}
          </span>
          <span
            class="footer-item"
            @click="handleStar(post)"
            :style="{ color: starredMap[post.id] ? '#FFD700' : '#888' }"
          >
            <svg viewBox="0 0 24 24" class="icon-svg">
              <path
                d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"
                :fill="starredMap[post.id] ? '#FFD700' : 'none'"
                :stroke="starredMap[post.id] ? '#FFD700' : '#999'"
                stroke-width="1.5"
              />
            </svg>
            {{ post.star_count }}
          </span>
        </div>
        <!-- 评论弹窗 -->
        <div v-if="showCommentFor === post.id" class="comment-modal">
          <div class="comment-modal-mask" @click="handleHideComments"></div>
          <div class="comment-modal-content">
            <div class="comment-modal-header">
              <span>评论</span>
              <span class="close-btn" @click="handleHideComments">×</span>
            </div>
            <div class="comment-list" v-if="!loadingComments">
              <div
                v-for="comment in commentsMap[post.id] || []"
                :key="comment.id"
                class="comment-item"
              >
                <img
                  class="comment-avatar"
                  :src="getUserAvatar(comment.user)"
                />
                <div class="comment-main">
                  <div class="comment-header">
                    <span class="comment-user">{{
                      getUserName(comment.user)
                    }}</span>
                    <span class="comment-time">{{
                      formatCommentTime(comment.created_at)
                    }}</span>
                  </div>
                  <div class="comment-content">{{ comment.content }}</div>
                  <div class="comment-actions">
                    <span class="comment-like" @click="handleLike(post)"
                      >👍 赞</span
                    >
                    <span
                      class="comment-reply-btn"
                      @click="handleShowComments(post)"
                      >回复</span
                    >
                    <span
                      class="comment-delete"
                      @click="handleDeleteComment(post, comment)"
                      >删除</span
                    >
                  </div>
                  <!-- 二级回复 -->
                  <div
                    v-if="comment.replies && comment.replies.length"
                    class="comment-replies"
                  >
                    <div
                      v-for="reply in comment.replies"
                      :key="reply.id"
                      class="comment-item"
                    >
                      <img
                        class="comment-avatar"
                        :src="getUserAvatar(reply.user)"
                      />
                      <div class="comment-main">
                        <div class="comment-header">
                          <span class="comment-user">{{
                            getUserName(reply.user)
                          }}</span>
                          <span class="comment-time">{{
                            formatCommentTime(reply.created_at)
                          }}</span>
                        </div>
                        <div class="comment-content">{{ reply.content }}</div>
                        <div class="comment-actions">
                          <span class="comment-like" @click="handleLike(post)"
                            >👍 赞</span
                          >
                          <span
                            class="comment-reply-btn"
                            @click="handleShowComments(post)"
                            >回复</span
                          >
                          <span
                            class="comment-delete"
                            @click="handleDeleteComment(post, reply)"
                            >删除</span
                          >
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div
                v-if="(commentsMap[post.id] || []).length === 0"
                class="comment-empty"
              >
                暂无评论
              </div>
            </div>
            <div v-else class="comment-loading">加载中...</div>
            <div class="comment-input-bar">
              <input
                v-model="commentInput"
                placeholder="写下你的评论..."
                class="comment-input"
                @keyup.enter="handleAddComment(post)"
                :disabled="!commentInput.trim()"
              />
              <button
                @click="handleAddComment(post)"
                class="comment-submit"
                :disabled="!commentInput.trim()"
              >
                发送
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作提示信息 -->
    <div v-if="showToast" class="toast-message">
      {{ toastMessage }}
    </div>

    <!-- 登录模态框 -->
    <LoginModal
      :show="showLoginModal"
      @close="hideLoginModal"
      @login-success="handleLoginSuccess"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import {
  getCurrentUserId,
  isLoggedIn,
  checkAuthStatus,
} from "../utils/auth.js";
import {
  getPosts,
  toggleLike,
  toggleStar,
  getComments,
  createComment,
  deleteComment,
  getUserActions,
  syncUserActions,
} from "../utils/posts.js";
import LoginModal from "../components/LoginModal.vue";

// 核心数据
const posts = ref([]);
const activeMenuId = ref(null);
const commentsMap = ref({}); // 存储各帖子的评论：{ postId: [comments] }
const likedMap = ref({}); // 点赞状态：{ postId: boolean }
const starredMap = ref({}); // 收藏状态：{ postId: boolean }

// 本地存储键名
const LIKED_POSTS_KEY = "discover_liked_posts";
const STARRED_POSTS_KEY = "discover_starred_posts";
const POSTS_COUNT_KEY = "discover_posts_count"; // 新增：保存帖子计数
const COMMENTS_KEY = "discover_comments"; // 新增：保存评论数据

// 评论相关
const showCommentFor = ref(null); // 当前显示评论的帖子ID
const commentInput = ref(""); // 评论输入框内容
const loadingComments = ref(false); // 评论加载状态
const showToast = ref(false); // 显示提示信息
const toastMessage = ref(""); // 提示信息内容

// 登录相关
const showLoginModal = ref(false); // 显示登录模态框

let ws = null; // WebSocket实例

// 从localStorage读取点赞和收藏状态
function loadUserActions() {
  try {
    const likedPosts = JSON.parse(
      localStorage.getItem(LIKED_POSTS_KEY) || "{}"
    );
    const starredPosts = JSON.parse(
      localStorage.getItem(STARRED_POSTS_KEY) || "{}"
    );
    likedMap.value = likedPosts;
    starredMap.value = starredPosts;
  } catch (error) {
    console.error("读取本地存储失败:", error);
    likedMap.value = {};
    starredMap.value = {};
  }
}

// 保存点赞状态到localStorage
function saveLikedPosts() {
  try {
    localStorage.setItem(LIKED_POSTS_KEY, JSON.stringify(likedMap.value));
  } catch (error) {
    console.error("保存点赞状态失败:", error);
  }
}

// 保存收藏状态到localStorage
function saveStarredPosts() {
  try {
    localStorage.setItem(STARRED_POSTS_KEY, JSON.stringify(starredMap.value));
  } catch (error) {
    console.error("保存收藏状态失败:", error);
  }
}

// 保存帖子计数到localStorage
function savePostsCount() {
  try {
    const postsCount = posts.value.map((post) => ({
      id: post.id,
      like_count: post.like_count,
      star_count: post.star_count,
      comment_count: post.comment_count,
    }));
    localStorage.setItem(POSTS_COUNT_KEY, JSON.stringify(postsCount));
  } catch (error) {
    console.error("保存帖子计数失败:", error);
  }
}

// 从localStorage加载帖子计数
function loadPostsCount() {
  try {
    const savedCounts = JSON.parse(
      localStorage.getItem(POSTS_COUNT_KEY) || "[]"
    );
    const countsMap = {};
    savedCounts.forEach((item) => {
      countsMap[item.id] = item;
    });

    // 更新帖子的计数
    posts.value.forEach((post) => {
      if (countsMap[post.id]) {
        post.like_count = countsMap[post.id].like_count;
        post.star_count = countsMap[post.id].star_count;
        post.comment_count = countsMap[post.id].comment_count;
      }
    });
  } catch (error) {
    console.error("加载帖子计数失败:", error);
  }
}

// 保存评论到localStorage
function saveComments() {
  try {
    localStorage.setItem(COMMENTS_KEY, JSON.stringify(commentsMap.value));
  } catch (error) {
    console.error("保存评论失败:", error);
  }
}

// 从localStorage加载评论
function loadComments() {
  try {
    const savedComments = JSON.parse(
      localStorage.getItem(COMMENTS_KEY) || "{}"
    );
    commentsMap.value = savedComments;
  } catch (error) {
    console.error("加载评论失败:", error);
    commentsMap.value = {};
  }
}

// 从后端加载用户操作状态
async function loadUserActionsFromServer() {
  try {
    const userId = getCurrentUserId();
    const serverData = await getUserActions(userId);

    // 合并服务器数据和本地数据
    const serverLiked = serverData.liked_posts || {};
    const serverStarred = serverData.starred_posts || {};

    // 更新本地状态
    Object.keys(serverLiked).forEach((postId) => {
      likedMap.value[postId] = serverLiked[postId];
    });

    Object.keys(serverStarred).forEach((postId) => {
      starredMap.value[postId] = serverStarred[postId];
    });

    // 保存到localStorage
    saveLikedPosts();
    saveStarredPosts();
  } catch (error) {
    console.error("从服务器加载用户操作失败:", error);
    // 如果服务器加载失败，继续使用本地数据
  }
}

// 初始化数据
onMounted(async () => {
  try {
    // 检查用户登录状态
    const isAuth = await checkAuthStatus();
    if (!isAuth) {
      showActionToast("请先登录");
      // 可以在这里跳转到登录页面
      return;
    }

    // 获取帖子列表
    posts.value = await getPosts();

    // 从localStorage加载用户操作状态（作为缓存）
    loadUserActions();

    // 从localStorage加载帖子计数
    loadPostsCount();

    // 从localStorage加载评论数据
    loadComments();

    // 从后端加载用户操作状态（同步最新数据）
    await loadUserActionsFromServer();

    // 初始化未操作过的帖子的状态
    posts.value.forEach((post) => {
      if (likedMap.value[post.id] === undefined) {
        likedMap.value[post.id] = false;
      }
      if (starredMap.value[post.id] === undefined) {
        starredMap.value[post.id] = false;
      }
    });

    // 全局WebSocket连接
    const wsUrl = "ws://localhost:8000/ws/posts/global/"; // 假设后端支持全局推送
    ws = new WebSocket(wsUrl);
    ws.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        // 用推送的最新数据覆盖页面数据
        const postToUpdate = posts.value.find((p) => p.id === data.post_id);
        if (postToUpdate) {
          postToUpdate.like_count = data.like_count;
          postToUpdate.star_count = data.star_count;
          postToUpdate.comment_count = data.comment_count;
          // 保存更新后的计数
          savePostsCount();
        }
      } catch (e) {
        console.error("WebSocket消息解析失败", e);
      }
    };
    ws.onclose = () => {
      ws = null;
    };
  } catch (error) {
    console.error("初始化失败:", error);
    showActionToast("加载数据失败，请重试");
  }
});

// 获取用户操作统计
function getUserActionStats() {
  const likedCount = Object.values(likedMap.value).filter(Boolean).length;
  const starredCount = Object.values(starredMap.value).filter(Boolean).length;
  const commentCount = Object.values(commentsMap.value).reduce(
    (total, comments) => {
      return total + (comments ? comments.length : 0);
    },
    0
  );
  return { likedCount, starredCount, commentCount };
}

// 显示操作提示
function showActionToast(message) {
  toastMessage.value = message;
  showToast.value = true;
  setTimeout(() => {
    showToast.value = false;
  }, 2000);
}

// 显示调试信息
function showDebugInfo() {
  const debugInfo = {
    likedPosts: likedMap.value,
    starredPosts: starredMap.value,
    comments: commentsMap.value,
    postsCount: posts.value.map((post) => ({
      id: post.id,
      like_count: post.like_count,
      star_count: post.star_count,
      comment_count: post.comment_count,
    })),
    localStorage: {
      liked: localStorage.getItem(LIKED_POSTS_KEY),
      starred: localStorage.getItem(STARRED_POSTS_KEY),
      count: localStorage.getItem(POSTS_COUNT_KEY),
      comments: localStorage.getItem(COMMENTS_KEY),
    },
  };
  console.log("调试信息:", debugInfo);
  alert("调试信息已输出到控制台，请按F12查看");
}

// 清除所有用户操作
function clearAllUserActions() {
  if (confirm("确定要清除所有点赞、收藏和评论记录吗？")) {
    likedMap.value = {};
    starredMap.value = {};
    commentsMap.value = {};
    saveLikedPosts();
    saveStarredPosts();
    saveComments();

    // 重置帖子计数到初始状态
    posts.value.forEach((post) => {
      // 从服务器获取的初始数据，减去用户操作的影响
      const initialLikeCount =
        post.like_count - (likedMap.value[post.id] ? 1 : 0);
      const initialStarCount =
        post.star_count - (starredMap.value[post.id] ? 1 : 0);
      const initialCommentCount =
        post.comment_count -
        (commentsMap.value[post.id] ? commentsMap.value[post.id].length : 0);
      post.like_count = Math.max(0, initialLikeCount);
      post.star_count = Math.max(0, initialStarCount);
      post.comment_count = Math.max(0, initialCommentCount);
    });

    // 保存重置后的计数
    savePostsCount();

    showActionToast("已清除所有操作记录");
  }
}

// 清理事件监听
onBeforeUnmount(() => {
  if (ws) {
    ws.close();
    ws = null;
  }
  window.removeEventListener("click", closeMenuOnOutsideClick);
});

// 工具函数：获取用户头像
function getUserAvatar(user) {
  return (
    user?.avatar ||
    "https://img2.baidu.com/it/u=3785284672,2189629152&fm=253&fmt=auto&app=138&f=JPEG?w=200&h=200"
  );
}

// 工具函数：获取用户名
function getUserName(user) {
  return user?.username || user?.name || user?.phone || "匿名用户";
}

// 工具函数：处理图片URL
function getPostImageUrl(image) {
  if (!image) return "";
  return image.startsWith("http") ? image : `http://127.0.0.1:8000${image}`;
}

// 工具函数：格式化时间显示
function formatCommentTime(timeString) {
  if (!timeString) return "";
  try {
    const date = new Date(timeString);
    const now = new Date();
    const diff = now - date;

    // 如果是今天，显示时分秒
    if (date.toDateString() === now.toDateString()) {
      return date.toLocaleTimeString("zh-CN", {
        hour12: false,
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
      });
    }

    // 如果是昨天
    const yesterday = new Date(now);
    yesterday.setDate(yesterday.getDate() - 1);
    if (date.toDateString() === yesterday.toDateString()) {
      return `昨天 ${date.toLocaleTimeString("zh-CN", {
        hour12: false,
        hour: "2-digit",
        minute: "2-digit",
      })}`;
    }

    // 其他情况显示完整日期时间
    return date.toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
    });
  } catch (error) {
    return timeString;
  }
}

// 菜单控制：切换显示/隐藏
function toggleMenu(id) {
  activeMenuId.value = activeMenuId.value === id ? null : id;
  // 绑定空白处关闭事件（避免重复绑定）
  window.removeEventListener("click", closeMenuOnOutsideClick);
  window.addEventListener("click", closeMenuOnOutsideClick);
}

// 点击空白处关闭菜单
function closeMenuOnOutsideClick(e) {
  const menuEl = document.querySelector(".action-menu");
  const btnEl = document.querySelector(".dots-btn");
  if (
    menuEl &&
    btnEl &&
    !menuEl.contains(e.target) &&
    !btnEl.contains(e.target)
  ) {
    activeMenuId.value = null;
  }
}

// 不感兴趣
function handleNotInterested(post) {
  activeMenuId.value = null;
  // 实际项目中添加接口调用
  posts.value = posts.value.filter((item) => item.id !== post.id);
}

// 举报功能
function handleReport(post) {
  activeMenuId.value = null;
  // 实际项目中添加接口调用和弹窗
  alert(`举报帖子：${post.id}`);
}

// 点赞功能
async function handleLike(post) {
  const isLiked = likedMap.value[post.id];
  const action = isLiked ? "unlike" : "like";

  try {
    // 先更新UI状态
    likedMap.value[post.id] = !isLiked;
    post.like_count += isLiked ? -1 : 1;
    saveLikedPosts();
    savePostsCount();

    // 调用后端API
    const response = await toggleLike(post.id, action);

    // 用后端返回的最新数据更新UI
    if (response && response.like_count !== undefined) {
      post.like_count = response.like_count;
      savePostsCount();
    }

    showActionToast(isLiked ? "取消点赞" : "点赞成功");
  } catch (error) {
    // 如果API调用失败，回滚UI状态
    likedMap.value[post.id] = isLiked;
    post.like_count += isLiked ? 1 : -1;
    saveLikedPosts();
    savePostsCount();

    console.error("点赞操作失败:", error);
    showActionToast("操作失败，请重试");
  }
}

// 收藏功能
async function handleStar(post) {
  const isStarred = starredMap.value[post.id];
  const action = isStarred ? "unstar" : "star";

  try {
    // 先更新UI状态
    starredMap.value[post.id] = !isStarred;
    post.star_count += isStarred ? -1 : 1;
    saveStarredPosts();
    savePostsCount();

    // 调用后端API
    const response = await toggleStar(post.id, action);

    // 用后端返回的最新数据更新UI
    if (response && response.star_count !== undefined) {
      post.star_count = response.star_count;
      savePostsCount();
    }

    showActionToast(isStarred ? "取消收藏" : "收藏成功");
  } catch (error) {
    // 如果API调用失败，回滚UI状态
    starredMap.value[post.id] = isStarred;
    post.star_count += isStarred ? 1 : -1;
    saveStarredPosts();
    savePostsCount();

    console.error("收藏操作失败:", error);
    showActionToast("操作失败，请重试");
  }
}

// 显示评论
async function handleShowComments(post) {
  showCommentFor.value = post.id;
  loadingComments.value = true;

  // 如果本地已有评论数据，直接显示
  if (commentsMap.value[post.id] && commentsMap.value[post.id].length > 0) {
    loadingComments.value = false;
    return;
  }

  try {
    const comments = await getComments(post.id);
    commentsMap.value[post.id] = comments || [];
    // 保存评论数据到localStorage
    saveComments();
  } catch (err) {
    console.error("加载评论失败", err);
    commentsMap.value[post.id] = [];
  } finally {
    loadingComments.value = false;
  }
}

// 隐藏评论
function handleHideComments() {
  showCommentFor.value = null;
  commentInput.value = "";
}

// 添加评论
async function handleAddComment(post) {
  if (!commentInput.value.trim()) return;

  const newComment = {
    id: Date.now(), // 临时ID，实际由后端生成
    user: {
      name: "当前用户",
      phone: "138****8888",
      avatar:
        "https://img2.baidu.com/it/u=3785284672,2189629152&fm=253&fmt=auto&app=138&f=JPEG?w=200&h=200",
    },
    content: commentInput.value,
    created_at: new Date().toLocaleString(),
  };

  // 前端临时更新（乐观UI）
  if (!commentsMap.value[post.id]) commentsMap.value[post.id] = [];
  commentsMap.value[post.id].unshift(newComment);
  post.comment_count += 1;
  commentInput.value = "";

  // 保存评论数据到localStorage
  saveComments();

  // 保存帖子计数到localStorage
  savePostsCount();

  // 显示操作提示
  showActionToast("评论发布成功");

  try {
    // 调用后端API保存评论
    const response = await createComment(post.id, newComment.content);

    // 如果后端返回了真实的评论数据，更新本地数据
    if (response && response.id) {
      newComment.id = response.id;
      newComment.created_at = response.created_at;
      newComment.user = response.user || newComment.user;
      saveComments();
    }
  } catch (err) {
    console.error("提交评论失败", err);
    // 失败时回滚
    commentsMap.value[post.id].shift();
    post.comment_count -= 1;
    saveComments(); // 重新保存评论
    savePostsCount(); // 重新保存计数
    showActionToast("评论发布失败，请重试");
  }
}

// 删除评论
async function handleDeleteComment(post, comment) {
  if (confirm("确定要删除这条评论吗？")) {
    // 从评论列表中删除
    const commentIndex = commentsMap.value[post.id].findIndex(
      (c) => c.id === comment.id
    );
    if (commentIndex > -1) {
      commentsMap.value[post.id].splice(commentIndex, 1);
      post.comment_count = Math.max(0, post.comment_count - 1);

      // 保存评论数据到localStorage
      saveComments();

      // 保存帖子计数到localStorage
      savePostsCount();

      showActionToast("评论已删除");

      // 调用后端API删除评论
      try {
        await deleteComment(comment.id);
      } catch (error) {
        console.error("删除评论失败:", error);
        // 如果后端删除失败，可以选择是否回滚本地状态
        // 这里选择不回滚，因为用户已经看到删除效果
      }
    }
  }
}

// 与服务器同步数据
async function syncWithServer() {
  try {
    showActionToast("正在同步数据...");

    const userId = getCurrentUserId();

    // 准备要同步的操作数据
    const actions = {
      liked_posts: likedMap.value,
      starred_posts: starredMap.value,
      comments: commentsMap.value,
    };

    // 同步用户操作状态
    await syncUserActions(userId, actions);

    // 从服务器重新加载最新状态
    await loadUserActionsFromServer();

    showActionToast("数据同步成功");
  } catch (error) {
    console.error("数据同步失败:", error);
    showActionToast("数据同步失败，请检查网络连接");
  }
}

// 显示登录模态框
function openLoginModal() {
  showLoginModal.value = true;
}

// 隐藏登录模态框
function hideLoginModal() {
  showLoginModal.value = false;
}

// 登录成功处理
function handleLoginSuccess(user) {
  showActionToast(`欢迎回来，${user.name || user.username}!`);
  // 登录成功后重新加载数据
  loadUserActionsFromServer();
}
</script>

<style scoped>
.discover-bg {
  background: #f5f6fa;
  min-height: 100vh;
  padding: 0;
  padding-top: 50px; /* 让内容刚好被头部导航压住一点 */
}
.discover-container {
  max-width: 700px;
  margin: 0 auto;
  padding: 40px 0 28px 0;
}

.user-stats {
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 2px 16px rgba(0, 0, 0, 0.07);
  margin-bottom: 32px;
  padding: 24px 32px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border: 1px solid #f0f1f3;
}

.stats-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.stats-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.stats-count {
  font-size: 24px;
  font-weight: bold;
  color: #00b2b1;
}

.clear-btn {
  background: #ff4d4f;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.2s;
}

.clear-btn:hover {
  background: #ff7875;
}

.debug-btn {
  background: #1890ff;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.2s;
}

.debug-btn:hover {
  background: #40a9ff;
}

.sync-btn {
  background: #52c41a;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.2s;
}

.sync-btn:hover {
  background: #73d13d;
}

.login-btn {
  background: #722ed1;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.2s;
}

.login-btn:hover {
  background: #9254de;
}
.post-card {
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 2px 16px rgba(0, 0, 0, 0.07);
  margin-bottom: 32px;
  padding: 32px 38px 18px 38px;
  position: relative;
  border: 1px solid #f0f1f3;
  transition: box-shadow 0.2s;
}
.post-card:hover {
  box-shadow: 0 6px 32px rgba(0, 178, 177, 0.1);
}
.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
}
.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 16px;
  border: 2px solid #f2f3f5;
  background: #f6fafd;
}
.user-info {
  display: flex;
  flex-direction: column;
}
.user-name {
  font-weight: 700;
  color: #222;
  font-size: 18px;
}
.user-tag {
  color: #00b2b1;
  font-size: 13px;
  margin-left: 6px;
}
.post-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #222;
}
.post-content {
  color: #222;
  font-size: 17px;
  line-height: 2.1;
  margin-bottom: 18px;
  word-break: break-all;
}
.post-image img {
  width: 320px;
  max-width: 100%;
  border-radius: 12px;
  margin: 10px 0 18px 0;
  object-fit: cover;
  background: #f8fafb;
  box-shadow: 0 1px 8px rgba(0, 0, 0, 0.03);
  display: block;
}
.post-footer {
  display: flex;
  align-items: center;
  gap: 48px;
  margin-top: 8px;
  font-size: 17px;
  color: #888;
  padding-bottom: 6px;
}
.footer-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #888;
  cursor: pointer;
  font-weight: 500;
  border-radius: 14px;
  padding: 2px 10px;
  transition: background 0.18s, color 0.18s;
}
.footer-item:hover {
  color: #00b2b1;
  background: #e6f7fa;
}
.icon-svg {
  width: 22px;
  height: 22px;
  margin-right: 2px;
}
.post-actions {
  position: absolute;
  right: 18px;
  top: 18px;
  z-index: 2;
}
.action-menu {
  position: absolute;
  right: 0;
  top: 32px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.12);
  min-width: 110px;
  padding: 8px 0;
  z-index: 10;
}
.menu-item {
  padding: 10px 18px;
  cursor: pointer;
  color: #222;
  font-size: 15px;
  transition: background 0.18s;
}
.menu-item:hover {
  background: #f5f6fa;
  color: #00b2b1;
}
.arrow-up {
  position: absolute;
  top: -8px;
  right: 18px;
  width: 0;
  height: 0;
  border-left: 8px solid transparent;
  border-right: 8px solid transparent;
  border-bottom: 8px solid #fff;
}
.comment-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}
.comment-modal-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
.comment-modal-content {
  background: #fff;
  border-radius: 20px;
  padding: 24px;
  width: 85%;
  max-width: 700px;
  max-height: 80vh;
  position: relative;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
}
.comment-modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.comment-modal-header span:first-child {
  font-size: 20px;
  font-weight: 600;
  color: #222;
}
.close-btn {
  cursor: pointer;
  font-size: 24px;
  color: #999;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background: #f5f5f5;
  color: #666;
}
.comment-list {
  flex: 1;
  overflow-y: auto;
  max-height: 400px;
  padding-right: 8px;
  margin-bottom: 16px;
}

.comment-list::-webkit-scrollbar {
  width: 6px;
}

.comment-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.comment-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.comment-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
.comment-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
  padding: 16px;
  background: #fafafa;
  border-radius: 12px;
  border: 1px solid #f0f0f0;
  transition: all 0.2s ease;
}

.comment-item:hover {
  background: #f5f5f5;
  border-color: #e0e0e0;
}
.comment-avatar {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 12px;
  border: 2px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}
.comment-main {
  flex: 1;
}
.comment-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
  flex-wrap: wrap;
  gap: 8px;
}
.comment-user {
  font-weight: 600;
  color: #333;
  font-size: 16px;
}
.comment-time {
  color: #999;
  font-size: 13px;
  background: #f0f0f0;
  padding: 2px 8px;
  border-radius: 12px;
  font-weight: 500;
}
.comment-content {
  color: #333;
  font-size: 15px;
  line-height: 1.6;
  margin-bottom: 12px;
  word-break: break-word;
  white-space: pre-wrap;
}
.comment-actions {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-top: 8px;
}
.comment-like {
  cursor: pointer;
  color: #666;
  font-size: 14px;
  padding: 4px 8px;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.comment-like:hover {
  background: #f0f0f0;
  color: #333;
}
.comment-reply-btn {
  cursor: pointer;
  color: #666;
  font-size: 14px;
  padding: 4px 8px;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.comment-reply-btn:hover {
  background: #f0f0f0;
  color: #333;
}

.comment-delete {
  cursor: pointer;
  color: #ff4d4f;
  font-size: 14px;
  padding: 4px 8px;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.comment-delete:hover {
  background: #fff2f0;
  color: #ff7875;
}
.comment-empty {
  text-align: center;
  color: #888;
  font-size: 15px;
  margin-top: 12px;
}
.comment-loading {
  text-align: center;
  color: #888;
  font-size: 15px;
  margin-top: 12px;
}
.comment-input-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: #fafafa;
  border-radius: 12px;
  border: 1px solid #f0f0f0;
  margin-top: 16px;
}
.comment-input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 20px;
  font-size: 14px;
  background: #fff;
  transition: all 0.2s ease;
}

.comment-input:focus {
  outline: none;
  border-color: #00b2b1;
  box-shadow: 0 0 0 2px rgba(0, 178, 177, 0.1);
}
.comment-submit {
  padding: 12px 24px;
  background: #00b2b1;
  color: #fff;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s ease;
  min-width: 80px;
}

.comment-submit:hover:not(:disabled) {
  background: #009e6d;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 178, 177, 0.3);
}

.comment-submit:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.comment-input:disabled {
  background: #f5f5f5;
  cursor: not-allowed;
}

.toast-message {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 16px;
  z-index: 10000;
  animation: fadeInOut 2s ease-in-out;
}

@keyframes fadeInOut {
  0% {
    opacity: 0;
    transform: translate(-50%, -50%) scale(0.8);
  }
  20% {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1);
  }
  80% {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1);
  }
  100% {
    opacity: 0;
    transform: translate(-50%, -50%) scale(0.8);
  }
}
</style>
